#pragma

#include <iostream>
#include <string>
#include <memory>
#include <unistd.h>

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Common.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace LogModule;

const int defaultsockfd = -1;
const int backlog = 8;

class TcpServer : public NoCopy
{
public:
    TcpServer(uint16_t port) : _port(port)
    {
    }

    void Init()
    {
        // 获取监听套接字
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd == 0)
        {
            LOG(LogLevel::FATAL) << "socket get error";
            exit(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket get success :" << _listensockfd;

        // 构建服务器地址
        InetAddr local(_port);
        // 绑定地址
        int n = bind(_listensockfd, local.NetAddrPtr(), local.NetAddrLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(BIND_ERR);
        }

        LOG(LogLevel::INFO) << "bind success" << _listensockfd;

        // 将socket设置为监听状态
        n = listen(_listensockfd, backlog);
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "listen error";
            exit(LISTEN_ERR);
        }

        LOG(LogLevel::INFO) << "listen success" << _listensockfd;
    }

    void Service(int sockfd, InetAddr &peer)
    {
        char buffer[1024];

        while (true)
        {
            // 实现使用 telnet 连接后发一个字符串，服务器给使用telnet的客户端返回打印一个字符串
            ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
            
            // 如果读取成功
            if(n > 0)
            {
                buffer[n] = 0;
                LOG(LogLevel::DEBUG) << peer.StringAddr() << " # " << buffer; 

                std::string echo_string = "echo #" + std::string(buffer);

                // echo 信息发给客户端
                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if(n == 0) // 对端把连接关闭了，读到了文件结尾
            {
                LOG(LogLevel::INFO) << peer.StringAddr() << " close";
                close(sockfd);
                break;
            }
            else // 读取失败
            {
                LOG(LogLevel::WARNING) << "read error";
                close(sockfd);
                break;
            }
        }
    }

    void Run()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // 使用输出型参数，获取链接
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);

            // 如果没有连接，accept阻塞等待
            int sockfd = accept(_listensockfd, CONV(peer), &len);
            if (sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error";
                continue;
            }
            InetAddr addr(peer);
            LOG(LogLevel::INFO) << "accept new connection: " << addr.StringAddr();

            Service(sockfd, addr);
        }

        _isrunning = false;
    }

    ~TcpServer() {}

private:
    uint16_t _port;
    int _listensockfd;

    bool _isrunning;
};